import { getRoutes } from './utils/sitemap';

const baseUrl = 'https://only-jdm.com';

export default {
  head() {
    // 无法直接闭包使用外层定义的baseUrl
    const baseUrl = 'https://only-jdm.com';
    let currentPath = this.$route.path.startsWith(`/${this.$i18n.locale}/`)
      ? this.$route.path.replace(`/${this.$i18n.locale}/`, '/')
      : this.$route.path === `/${this.$i18n.locale}`
      ? '/'
      : this.$route.path;

    currentPath = currentPath.replace(/\/$/, '');
    // 生成所有语言版本的 hreflang 链接
    const links = [
      // 添加 x-default 链接 (指向默认语言版本)
      {
        hid: 'alternate-hreflang-x-default',
        rel: 'alternate',
        hreflang: 'x-default',
        href: `${baseUrl}${currentPath || '/'}`
      },
      // 生成各语言版本的链接
      ...this.$i18n.locales.map((locale) => ({
        hid: `alternate-hreflang-${locale.code}`,
        rel: 'alternate',
        hreflang: locale.code,
        href:
          locale.code === this.$i18n.defaultLocale
            ? `${baseUrl}${currentPath || '/'}`
            : `${baseUrl}/${locale.code}${currentPath}`
      }))
    ];
    return {
      title: this.$t('seo.title'),
      htmlAttrs: {
        ...this.$nuxtI18nHead({ addSeoAttributes: true }).htmlAttrs
      },
      meta: [
        { charset: 'utf-8' },
        ...(process.env.NUXT_ENV_ENV === 'prod'
          ? []
          : [{ name: 'robots', content: 'noindex, nofollow' }]),
        { name: 'viewport', content: 'width=device-width, initial-scale=1, minimum-scale=1' }, // 优化移动端
        { name: 'theme-color', content: '#ffffff' },
        {
          name: 'google-site-verification',
          content: 'uu9Iw0UDV7HQpAHky7-cH0QgkyyQoDAXkKnCwmGAC34'
        },
        { 'http-equiv': 'Content-Language', content: this.$i18n.locale },
        { hid: 'description', name: 'description', content: this.$t('seo.description') },
        // Open Graph
        { hid: 'og:title', property: 'og:title', content: this.$t('seo.title') },
        {
          hid: 'og:description',
          property: 'og:description',
          content: this.$t('seo.description')
        },
        { hid: 'og:locale', property: 'og:locale', content: this.$i18n.locale },
        { hid: 'og:image', property: 'og:image', content: `${baseUrl}/logo.jpg` }, // 分享缩略图
        { hid: 'og:url', property: 'og:url', content: `${baseUrl}${this.$route.path}` }, // 当前页 URL
        // Twitter Card
        { hid: 'twitter:card', name: 'twitter:card', content: 'summary_large_image' },
        { hid: 'twitter:title', name: 'twitter:title', content: this.$t('seo.title') },
        {
          hid: 'twitter:description',
          name: 'twitter:description',
          content: this.$t('seo.description')
        },
        {
          hid: 'twitter:image',
          name: 'twitter:image',
          content: `${baseUrl}/logo.jpg`
        },
        // Canonical URL
        {
          hid: 'canonical',
          rel: 'canonical',
          href: baseUrl + (this.$route.path.replace(/\/$/, '') || '/')
        },
        // 多语言备用链接
        ...this.$i18n.locales
          .filter((locale) => locale.code !== this.$i18n.locale)
          .map((locale) => ({
            hid: `og:locale:alternate:${locale.code}`,
            property: 'og:locale:alternate',
            content: locale.iso
          }))
      ],
      link: [
        { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
        {
          rel: 'preload',
          as: 'image',
          href: '/favicon.ico'
        },
        ...links
      ],
      // JSON-LD 结构化数据（示例）
      __dangerouslyDisableSanitizers: ['script'],
      script: [
        {
          type: 'application/ld+json',
          innerHTML: JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'WebSite',
            name: this.$t('seo.title'),
            url: baseUrl,
            image: `${baseUrl}/logo.jpg`,
            description: this.$t('seo.description')
          })
        }
      ]
    };
  },

  ssr: true,
  components: true,
  buildModules: [
    [
      '@nuxtjs/vuetify',
      {
        defaultAssets: {
          font: false,
          icons: 'mdiSvg'
        }
      }
    ]
  ],
  serverMiddleware: ['~/middleware/performance.js', '~/middleware/uri-validation.js'],
  modules: [
    '@nuxtjs/i18n',
    '@nuxtjs/sitemap',
    '@nuxtjs/robots',
    '@nuxtjs/axios',
    'cookie-universal-nuxt',
    '@nuxtjs/proxy',
    '@nuxtjs/redirect-module'
  ],
  plugins: ['~/plugins/axios.js', '~/plugins/promise-polyfill.js', '~/plugins/analytics.client.js'],
  sitemap: {
    hostname: baseUrl,
    cacheTime: 3600000, // 1小时缓存（单位：毫秒）
    i18n: {
      locales: ['en', 'ja', /* 'zh-Hans', */ 'zh-Hant'],
      routesNameSeparator: '___'
    },
    defaults: {
      changefreq: 'daily',
      priority: 0.8, // 默认优先级设为0.8（三级页面）
      lastmod: new Date().toISOString()
    },
    routes: getRoutes
  },
  robots:
    process.env.NUXT_ENV_ENV === 'prod'
      ? {
          UserAgent: '*',
          Disallow: '',
          Sitemap: 'https://only-jdm.com/sitemap.xml'
        }
      : {
          UserAgent: '*',
          Disallow: '/'
        },
  i18n: {
    locales: [
      { code: 'en', iso: 'en-US', file: 'en.js' }, // 英文
      { code: 'ja', iso: 'ja-JP', file: 'ja.js' }, // 日语
      // { code: 'zh-Hans', iso: 'zh-CN', file: 'zhHans.js' }, // 中文简体
      { code: 'zh-Hant', iso: 'zh-TW', file: 'zhHant.js' } // 中文繁体
    ],
    strategy: 'prefix_except_default',
    defaultLocale: 'en', // 默认语言
    seo: true,
    detectBrowserLanguage: false,
    // 新增：懒加载语言文件
    lazy: true,
    langDir: 'lang/', // 语言文件目录
    baseUrl,
    vueI18n: {
      fallbackLocale: 'en', // 回退语言
      messages: {
        en: require('./lang/en.js').default,
        ja: require('./lang/ja.js').default,
        // 'zh-Hans': require('./lang/zhHans.js').default,
        'zh-Hant': require('./lang/zhHant.js').default
      }
    }
  },
  axios: {
    baseURL: `${process.env.NUXT_ENV_API_BASE_URL}/api/zuche`
  },
  // 开发环境代理 只在开发环境生效
  proxy:
    process.env.NODE_ENV === 'development'
      ? {
          '/api/zuche': {
            target: process.env.NUXT_ENV_API_BASE_URL,
            debug: true,
            // pathRewrite: { '^/api': '' }, // 可选：重写路径
            changeOrigin: true, // 解决跨域
            // 开发环境解决跨域 token无法传递的问题
            onProxyRes(proxyRes, req, res) {
              if (req.url === '/api/zuche/user/login') {
                Object.keys(proxyRes.headers).forEach((key) => {
                  if (key.toLowerCase() === 'set-cookie') {
                    const cookies = proxyRes.headers[key];
                    if (Array.isArray(cookies)) {
                      cookies.forEach((cookie) => {
                        if (cookie.startsWith('token')) {
                          const tokenStr = cookie.split(';')[0];
                          const token = tokenStr.split('=')[1];
                          res.setHeader('token', token);
                        }
                      });
                    }
                  }
                });
              }
            }
          }
        }
      : undefined,
  telemetry: false,
  // redirect: [
  //   { from: '^/h5$', to: '/', statusCode: 301 },
  //   { from: '^/h5/(.*)$', to: '/$1', statusCode: 301 },
  //   { from: '^/zh-Hans$', to: '/zh-Hant', statusCode: 301 },
  //   { from: '^/zh-Hans/(.*)$', to: '/zh-Hant/$1', statusCode: 301 },
  //   { from: '^/zhHant/(.*)$', to: '/zh-Hant/$1', statusCode: 301 }
  // ],
  buildDir: process.env.BUILD_DIR || '.nuxt'
};
